<template>
  <div class="modelingSettings">
    <div class="modelingSettingsLeft" ref="modelingSettingsLeft">
      <panel-aside @onSearch="productSearch" ref="productInfo"></panel-aside>
    </div>
    <div class="modelingSettingsRight">
      <div class="kan">
        <h2>{{ productCheck.productName }}</h2>
        <Button class="action" type="primary"> <a
            href="https://images.tospurfang.com/doc/%E5%BB%BA%E6%A8%A1%E8%AE%BE%E7%BD%AE%E6%93%8D%E4%BD%9C%E8%AF%B4%E6%98%8E.pdf"
            style="color:#fff;" target="_blank">查看操作指引</a>
        </Button>
      </div>
      <Tabs type="card" v-model="setSwitch" :animated="false">
        <TabPane label="楼栋模型" name="buildingModel">
          <div class="modelTit">
            <span>已选{{ selectionArr.length }}项</span>
            <Button :disabled="selectionArr.length == 0" @click="advanceSale"
              v-if="unlocking('0103021000')">提前开售</Button>
            <Button style="margin-left: 10px" :disabled="selectionArr.length == 0"
              @click="deleteBuildFun()" v-if="unlocking('0103020200')">删除楼栋</Button>
            <Button style="margin-left: 10px" type="primary" @click="newBuildingFlag = true"
              v-if="unlocking('0103020100')" :disabled="!newBuildingBtn">新建楼栋</Button>
          </div>
          <div class="tab position-relative">
            <Table border ref="TableHeight" @on-selection-change="selectionChange"
              :max-height="onresizeHeight" :columns="columnList" :data="dataList"></Table>
            <Spin fix v-show="loading">
              <Icon type="load-c" size="18" class="dt-loading"></Icon>
              <div>Loading</div>
            </Spin>
          </div>
        </TabPane>
        <TabPane label="产品信息" name="product">
          <div class="productBox">
            <div class="productBtn">
              <Button type="primary" class="fr" @click="editProductInfo"
                v-if="unlocking('0103020300')">编辑信息</Button>
            </div>
            <div class="productInfo">
              <ul class="flex flex-wrap">
                <li v-for="(item, index) in productInfoList" :key="index" style="width: 50%"
                  class="flex">
                  <p class="right">{{ item.name }}：</p>
                  <p v-if="item.type == 'key'" class="ell pro-text" :title="
                      $formatter.switchName(item.arrKey, productInfo[item.key])
                    ">
                    {{
                      $formatter.switchName(item.arrKey, productInfo[item.key])
                    }}
                  </p>
                  <p v-if="item.type == 'text'" class="ell pro-text"
                    :title="productInfo[item.key]">
                    {{ productInfo[item.key] ||'-'}}<span v-show="productInfo[item.key]">
                      {{ item.unit }}</span>
                  </p>
                  <p v-if="item.key =='commissionFeesType'" class="ell pro-text">
                    <span v-if="productInfo.isJumpCommission">
                      {{productInfo.commissionFeesStartValue}}-{{productInfo.commissionFeesEndValue}}
                      <i>{{productInfo.commissionFeesType==1?'%':'元'}}</i>
                    </span>
                    <span v-else>
                      {{productInfo.commissionFeesStartValue}}
                      <i>{{productInfo.commissionFeesType==1?'%':'元'}}</i>
                    </span>
                  </p>
                  <p v-if="item.type == 'boolean'&&item.key == 'isIndexCal'">
                    {{ productInfo[item.key] == "1" ? "参与" : "未参与" }}
                  </p>
                  <p v-if="item.type == 'boolean'&&item.key == 'isJumpCommission'">
                    {{ productInfo[item.key] == "1" ? "是" : "否" }}
                  </p>
                </li>
              </ul>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </div>
    <Modal v-model="newBuildingFlag" title="新建楼栋" width="500" :footerHide="true">
      <new-building v-if="newBuildingFlag" :buildDrop="buildDrop" @onClose="closeModal"
        :productId="productCheck.productId" @onSearch="initData" @onRefresh="refreshLeft">
      </new-building>
    </Modal>
    <Modal v-model="editBuildingFlag" title="编辑楼栋" @on-cancel="editBuildingCancel" width="500"
      :footerHide="true">
      <div class="editBuild">
        <span><em>*</em> 楼栋号：</span><Input style="width: 200px"
          v-model="checkBuildInfo.buildingName" @on-keyup="inputBuildingName"
          placeholder="请填写楼栋号"></Input>
      </div>
      <div class="newBuildingFooter">
        <Button @click="editBuildingCancel">取消</Button>
        <Button type="info" @click="editBuildingOk">确认</Button>
      </div>
    </Modal>
    <Modal v-model="batchFlag" title="请选择需要关联的批次" width="70%" :footer-hide="true"
      @on-cancel="batchCancel">
      <div class="tab">
        <div class="pici"><Button type="primary" @click="goBuildingConfigure">新建批次</Button>
        </div>
        <Table :columns="batchColumns" :data="batchData" border max-height="400">
        </Table>
        <!-- 分页 -->
        <page v-if="pageData.total!=0" :pageData="pageData" @pageOnChangeFun="pageOnChangeFun"
          @pageOnPageSizeChangeFun="pageOnPageSizeChangeFun"></page>
      </div>
    </Modal>
    <building-add ref="profile" :buildingId="curBuildingId" @updataData="updataData">
    </building-add>
    <Modal v-model="advanceSaleFlag" title="提前开售" width="500" :footerHide="true">
      <advance-sale :productType="productCheck.productType" :selectionArr="selectionArr"
        @cancelClose="cancelClose" @initData="initData"></advance-sale>
    </Modal>
    <Modal v-model="advanceSaleDetailesFlag" title="审核情况" width="500" :footerHide="true">
      <advance-sale-details :examineDetails="examineDetails" :shenheStatus="shenheStatus"
        @detailsCancel="detailsCancel"></advance-sale-details>
    </Modal>
  </div>
</template>

<script>
  import advanceSale from './components/advanceSale.vue'
  import advanceSaleDetails from './components/advanceSaleDetails.vue'
  import buildingAdd from './components/buildingAdd.vue'
  import panelAside from './components/panelAside.vue'
  import advanceSaleMgr from '@/biz/advanceSaleReview/advanceSaleReview'
  import openingBatchMgr from '@/biz/buildingManagement/openingBatch'
  import newBuilding from './components/newBuilding.vue'
  import columnsAll from './components/columns'
  import tool from '@/common/tool.js'
  export default {
    components: {
      buildingAdd,
      panelAside,
      newBuilding,
      advanceSale,
      advanceSaleDetails,
    },
    data() {
      return {
        pageData: {
          total: 0,
          current: 1,
          rows: 50,
          pageSizeOpts: [50, 40, 30, 20, 10],
        },
        shenheStatus: '',
        examineDetails: {},
        advanceSaleFlag: false, //提前开售申请框
        advanceSaleDetailesFlag: false,
        buildingNameList: '',
        productType: '',
        curBuildingId: '',
        dictionaryData: JSON.parse(tool.getStorage('dictionaryData')),
        buildDrop: [], // 产品下建筑类型下拉
        buildingArr: [], // 所有建筑类型
        loading: false,
        batchFlag: false,
        batchColumns: columnsAll.batchColumns,
        batchData: [], // 案场关联批次列表
        editBuildingFlag: false, // 编辑楼栋
        newBuildingFlag: false, // 新增楼栋
        newBuildingBtn: true, // 新增楼栋按钮
        setSwitch: 'buildingModel',
        columnList: columnsAll.columnList,
        dataList: [], // 楼栋列表
        onresizeHeight: 0,
        productCheck: {}, //选中产品
        productInfoList: columnsAll.productInfoList, // 产品信息
        productInfo: {},
        selectionArr: [], //选择楼栋
        checkBuildInfo: {}, // 选中楼栋
      }
    },
    computed: {},
    watch: {},
    methods: {
      inputBuildingName() {
        let specialWords = this.$dt.dictInfo().specialWords[0].key
        let reg = new RegExp(specialWords, 'im')
        this.checkBuildInfo.buildingName = this.checkBuildInfo.buildingName.replace(reg, '')
      },
      detailsCancel() {
        this.advanceSaleDetailesFlag = false
      },
      cancelClose() {
        this.advanceSaleFlag = false
      },
      goBuildingConfigure() {
        this.$router.push({
          name: 'buildingConfigure',
          params: {
            fromCustomer: 'openingBatch',
          },
        })
      },
      getExamineDetails(val, param) {
        this.shenheStatus = val.status
        if (
          (param == 'status' &&
            (val.status == 'REJECT' || val.status == 'WAIT_APPROVE')) ||
          (param == 'date' && val.recId)
        ) {
          this.advanceSaleDetailesFlag = true
          let params = {
            recId: val.recId,
          }

          advanceSaleMgr.getPreSaleRec(params).then((res) => {
            this.examineDetails = res
          })
        }
      },
      updataData() {
        this.initData()
      },
      // 选择产品
      productSearch(parmas) {
        if (parmas) {
          this.newBuildingBtn = true
          this.productCheck = { ...parmas }
          this.initData()
          this.getProductInfo()
        } else {
          this.newBuildingBtn = false
        }

      },
      /**
       * 刷新左侧列表
       *
       */
      refreshLeft() {
        this.$refs.productInfo.getPlateTreeData(this.productCheck)
      },
      // 楼栋模型列表数据
      initData() {
        let params = {
          productId: this.productCheck.productId,
        }
        this.selectionArr = []
        this.loading = true
        advanceSaleMgr
          .getBuildingListDetail(params)
          .then((res) => {
            if (res) {
              this.dataList = res
              this.dataList.forEach((item) => {
                if (
                  item.status == 'CAN' ||
                  item.status == 'WAIT_APPROVE' ||
                  item.status == 'APPROVED'
                ) {
                  item['_disabled'] = true
                }
              })
            } else {
              this.dataList = []
            }
            this.loading = false
            this.$nextTick(function() {
              this.onresizeHeight = this.$tool.getTableHeight(
                this.$refs.TableHeight
              )
            })
          })
          .catch((res) => {
            this.$Message.error(res)
            this.dataList = []
            this.loading = false
            this.$nextTick(function() {
              this.onresizeHeight = this.$tool.getTableHeight(
                this.$refs.TableHeight
              )
            })
          })
      },
      // 列表选择
      selectionChange(selection) {
        this.selectionArr = selection
      },
      // 提前开售
      advanceSale() {
        let flag = this.selectionArr.some((item) => {
          return item.status != 'CANNOT' && item.status != 'REJECT'
        })
        if (flag) {
          this.$Message.warning('只能选择未开售的楼栋。')
        } else {
          this.advanceSaleFlag = true
        }
      },
      // 删除楼栋
      deleteBuildFun(singleObj = 0) {
        let buildingEdit = singleObj ? [singleObj] : this.selectionArr
        let params = {
          buildingIds: buildingEdit.map((item) => {
            return item.buildingId
          }),
        }
        this.$Modal.confirm({
          title: '删除楼栋',
          content: `<p>请确认,您要删除${buildingEdit.length}个楼栋，删除后不可恢复！</p>`,
          onOk: () => {
            advanceSaleMgr
              .deleteBuild(params)
              .then((res) => {
                this.$Message.info('删除成功。')
                this.refreshLeft()
              })
              .catch((res) => this.$Message.error(res))
          },
          onCancel: () => {
            this.$Message.info('您取消了删除。')
          },
        })
      },
      closeModal() {
        this.newBuildingFlag = false
      },
      getProductInfo() {
        let params = {
          productId: this.productCheck.productId,
        }
        this.buildDrop = []
        advanceSaleMgr
          .productInfo(params)
          .then((res) => { //coopMode 4大包销 5小包销
            this.productInfo = { ...res }
            this.buildingArr.forEach((item) => {
              if (res.buildingTypes.indexOf(item.key) > -1) {
                this.buildDrop.push(item)
              }
            })
            this.productInfo.buildingTypesName = this.buildDrop
              .map((item) => {
                return item.value
              })
              .join(',')
          })
          .catch((res) => this.$Message.error(res))
      },
      editProductInfo() {
        this.$router.push({
          name: 'product',
          params: this.productInfo,
        })
      },
      searchHouse(row) {
        console.log(row, 'current');
        this.productType = row.productType
        this.curBuildingId = row.buildingId
        if (!row.isModeled) {
          this.$refs.profile.show()
        } else {
          this.$router.push({
            path: '/buildingModeling/housingModel',
            query: {
              productId: this.productCheck.productId,
              buildingId: row.buildingId,
              productType: this.productType
            },
          })
        }
      },
      goOpeningBatch(row) {
        this.batchFlag = true
        this.checkBuildInfo = { ...row }
        this.getBatchData()
      },
      // 批次列表
      getBatchData() {
        let params = {
          housesId: this.$dt.buildInfo().housesId,
          page: this.pageData.current,
          rows: this.pageData.rows,
        }
        openingBatchMgr.batchList(params)
          .then((res) => {
            this.batchData = res.list
            this.pageData.total = res.total
          })
          .catch((res) => this.$Message.error(res))
      },
      associatedBatch(row) {
        this.$Modal.confirm({
          title: '关联批次',
          content: `<p>请确认，是否将楼栋“${this.checkBuildInfo.buildingName}”关联至批次“${row.batchName}”？</p>`,
          onOk: () => {
            let parmas = {
              batchId: row.batchId,
              buildingId: this.checkBuildInfo.buildingId,
              batchBindId: this.checkBuildInfo.batchBindId,
            }
            openingBatchMgr.batchBind(parmas)
              .then((res) => {
                this.batchFlag = false
                this.initData()
                this.$Message.info('关联成功。')
              })
              .catch((res) => this.$Message.error(res))
          },
          onCancel: () => {
            this.$Message.info('你取消了关联。')
          },
        })
      },
      batchCancel() {
        this.batchFlag = false
      },
      editBuildingClick(row) {
        this.checkBuildInfo = { ...row }
        this.editBuildingFlag = true
      },
      editBuildingCancel() {
        this.editBuildingFlag = false
      },
      editBuildingOk() {
        if (this.checkBuildInfo.buildingName == '') {
          this.$Message.error('楼栋号必填！')
          return false
        }
        let params = {
          productId: this.productCheck.productId,
          housesId: this.$dt.buildInfo().housesId,
          buildingId: this.checkBuildInfo.buildingId,
          buildingName: this.checkBuildInfo.buildingName,
        }
        advanceSaleMgr
          .editBuild(params)
          .then((res) => {
            this.editBuildingFlag = false
            this.initData()
          })
          .catch((res) => this.$Message.error(res))
      },
      // 分页 页码改变事件
      pageOnChangeFun(page) {
        this.getBatchData()
      },
      // 分页 每页条数改变事件
      pageOnPageSizeChangeFun(rows) {
        this.getBatchData()
      },
    },
    watch: {
      setSwitch(val) {
        if (val == 'buildingModel') this.initData()
      },
    },
    created() {
      this.buildingArr = []
      this.dictionaryData.productType.forEach((item) => {
        this.buildingArr = this.buildingArr.concat(item.children)
      })
    },
    mounted() {
      //发送this 到 js 文件里
      columnsAll.sendThis(this)
      let _this = this
      _this.onresizeHeight = this.$tool.getTableHeight(this.$refs.TableHeight)
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            _this.onresizeHeight = _this.$tool.getTableHeight(
              _this.$refs.TableHeight
            )
          }, 10)
        })()
      }
    },
  }
</script>
<style lang='scss' scoped>
  .modelingSettings {
    margin-bottom: 20px;
    padding: 10px;
    display: flex;
    width: 100%;
    overflow: hidden;

    .modelingSettingsLeft {
      height: 100%;
      overflow-y: scroll;
      overflow-x: hidden;
      flex: 0 0 300px;

      .proBox {
        border-bottom: 1px solid #dcdee2;
        padding: 5px 0;
        cursor: pointer;

        .pro {
          padding: 5px 10px;

          p.p1 {
            margin-bottom: 10px;
          }

          p.p2 {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
          }
        }
      }

      .proBg {
        background: skyblue;
        color: #fff;
      }
    }

    .modelingSettingsRight {
      width: calc(100% - 300px);
      padding: 10px;

      .kan {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }

      h2 {
        margin: 10px 0;
      }

      .modelTit {
        padding: 10px;
        display: flex;
        flex-direction: row;

        span {
          flex: 1;
        }
      }

      .tab {
        margin: 10px 0;
        width: 100%;
        height: 100%;
      }

      .productBox {
        width: 100%;
        padding: 20px;
        border: 1px #dcdee2 solid;

        .productBtn {
          overflow: hidden;
        }

        .productInfo {
          ul {
            padding: 10px 100px;

            li {
              .pro-text {
                width: calc(100% - 150px);
              }

              font-size: 16px;
              line-height: 45px;
            }
          }
        }
      }
    }
  }

  .newBuildingFooter {
    padding-top: 16px;
    text-align: center;

    button {
      width: 90px;
      margin: 0 10px;
    }
  }

  .editBuild {
    height: 100px;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding-left: 50px;

    span {
      em {
        color: red;
      }
    }
  }

  .ivu-spin-fix {
    background-color: rgba(255, 255, 255, 0.35);
  }

  .pici {
    text-align: right;
    padding: 10px;
  }
</style>